

import 'http_code.dart';
import 'http_response.dart';

extension FutureExtension on Future<HttpResponse> {
  Future<HttpResponse> handler<T>(
    T Function(Map<String, dynamic>)? fromJson,
    void Function(HttpResponse response)? handleError,
    Function(int? code)? errorCodeListener,
  ) {
    return then((response) {

      if (response.isSuccess) {
        if (fromJson != null && response.data != null) {
          try {
            dynamic data;
            if (response.data is List) {
              data = List<T>.from(
                  (response.data as List).map((e) => fromJson.call(e)));
            }
            // else if (response.data is Map &&
            //     response.data.keys.contains('list')) {
            //   data = List<T>.from(
            //       (response.data['list'] as List).map((e) => fromJson.call(e)));
            // }
            else {
              data = fromJson.call(response.data);
            }
            // dynamic data = response.data is List ? List<T>.from((response.data as List).map((e) => fromJson.call(e))) : fromJson.call(response.data);
            response.data = data;
          } catch (e) {
            response.data = null;
            response.status = HttpCode.code200;
            response.message = "解析错误:$e";
          }
        }
      } else {
        handleError?.call(response);
        errorCodeListener?.call(response.status);
      }
      return response;
    }, onError: (error) {
      if (error is HttpResponse) {
        HttpResponse err = error;
        handleError?.call(err);
        errorCodeListener?.call(err.status);
        return err;
      } else {
        return HttpResponse(message: error.toString());
      }
    });
  }
}
